package cn.com.panda.net;

import android.content.Context;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.common.auth.OSSAuthCredentialsProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;

import cn.com.panda.net.http.interfaces.HttpWebUtils;
import cn.com.panda.net.http.request.HttpRequest;

/**
 * created by liujunlin on 2022/3/17 09:26
 */
public class CMApiManager {

    public static void uploadImage(Context context, String imagePath, String ossFileName, HttpRequest.OnResponseLister onResponseLister){
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        String stsServer = "https://api3.bseera.com/sts/token";
        // 推荐使用OSSAuthCredentialsProvider。token过期可以及时更新。
        OSSCredentialProvider credentialProvider = new OSSAuthCredentialsProvider(stsServer);

        // 配置类如果不设置，会有默认配置。
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(300 * 1000); // 连接超时，默认15秒。
        conf.setSocketTimeout(300 * 1000); // socket超时，默认15秒。
        conf.setMaxConcurrentRequest(10); // 最大并发请求数，默认5个。
        conf.setMaxErrorRetry(3); // 失败后最大重试次数，默认2次。

        OSS oss = new OSSClient( context, endpoint, credentialProvider);
        // 构造上传请求。
        // 依次填写Bucket名称（例如examplebucket）、Object完整路径（例如exampledir/exampleobject.txt）和本地文件完整路径（例如/storage/emulated/0/oss/examplefile.txt）。
        // Object完整路径中不能包含Bucket名称。
        PutObjectRequest put = new PutObjectRequest("searchimg", ossFileName, imagePath);

        try {
            PutObjectResult putResult = oss.putObject(put);

            Log.d("PutObject", "UploadSuccess");
            Log.d("ETag", putResult.getETag());
            Log.d("RequestId", putResult.getRequestId());

            String ossurl = "https://img.bseera.com/"+ossFileName;
            onResponseLister.onResponse(ossurl);

        } catch (ClientException e) {
            // 客户端异常，例如网络异常等。
            e.printStackTrace();
            Log.e("ossupload:",e.getMessage());
            onResponseLister.onError("上传文件失败"+e.getMessage());
        } catch (ServiceException e) {
            // 服务端异常。
            Log.e("RequestId", e.getRequestId());
            Log.e("ErrorCode", e.getErrorCode());
            Log.e("HostId", e.getHostId());
            Log.e("RawMessage", e.getRawMessage());
            e.printStackTrace();
            onResponseLister.onError("上传文件失败"+e.getMessage());
        }
    }

}
